<template>
  <div class="breakdown-container">
    <el-form :inline="true" :model="selectForm" class="select-box">
      <el-form-item label="平台">
        <el-select v-model="selectForm.platform" clearable placeholder="请选择" size="small" style="margin-right: 10px;" @change="changePlatforms">
          <el-option v-for="item in selectForm.platforms" :key="item.label" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="平台版本">
        <el-select v-model="selectForm.version" clearable placeholder="请选择" size="small">
          <el-option v-for="(val, key) in selectForm.versions" :key="key" :label="val" :value="val"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
        size="small"
        v-model="selectForm.dateTimePick"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="small" :loading="false" @click="getEchartData">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="breakdown-data">
      <h4 class="data-title">崩溃数据</h4>
      <el-row type="flex" justify="space-around">
        <el-col :span="3" style="background: #00c0ef;">
          <span class="figure"><label>{{ crashRate }}</label> %</span>
          <span class="declare">崩溃率</span>
        </el-col>
        <el-col :span="3" style="background: #F56C6C;">
          <span class="figure"><label>{{ crashCnt }}</label> 次</span>
          <span class="declare">崩溃发生次数</span>
        </el-col>
        <el-col :span="3" style="background: #605ca8;">
          <span class="figure"><label>{{ crashUserCnt }}</label> 位</span>
          <span class="declare">影响用户数</span>
        </el-col>
        <el-col :span="3" style="background: #00A65A;">
          <span class="figure"><label>{{ userCnt }}</label> 位</span>
          <span class="declare">使用用户数</span>
        </el-col>      
      </el-row>
    </div>
    <div class="breakdown-tendency">
      <h4 class="tendency-title">崩溃趋势图</h4>
      <div id="tendency-echart" style="width: 100%; height:280px;" v-loading="tendencyData.isLoading"></div>
    </div>
    <div class="breakdown-rank">
      <h4 class="rank-title">崩溃排行榜</h4>
      <el-row :gutter="20" class="top5-box">
        <el-col :span="8">
          <div id="os-versions-echart" style="width: 100%; height: 240px;" v-loading="osVersionsData.isLoading"></div>
        </el-col>
        <el-col :span="8">
          <div id="equitments-echart" style="width: 100%; height: 240px;" v-loading="equitmentsData.isLoading"></div>
        </el-col>
        <el-col :span="8">
          <div id="app-versions-echart" style="width: 100%; height: 240px;" v-loading="appVersionsData.isLoading"></div>
        </el-col>        
      </el-row>
    </div>
  </div>
</template>
<script>
  import echarts from 'echarts'
  // import lodash from 'lodash'
  import moment from 'moment'

  export default {
    data () {
      return {
        selectForm: {
          platform: '',
          version: '',
          platforms: [
            {label: '全部', value: '', versions: []}
          ],
          versions: '',
          dateTimePick: [moment().format('YYYY-MM-DD 00:00:00'), moment().format('YYYY-MM-DD HH:mm:ss')]
        },
        crashRate: '',
        crashCnt: '',
        crashUserCnt: '',
        userCnt: '',
        tendencyData: {
          isLoading: false,
          dateList: '',
          userCounts: ''
        },
        echarts: { // 实例
          tendency: '',
          osVersions: '',
          equitments: '',
          appVersions: ''
        },
        rankColor: '#4793C0',
        // rankColor: '#3B73C3',
        osVersionsData: {
          isLoading: false,
          resultData: '',
          max: 0
        },
        equitmentsData: {
          isLoading: false,
          resultData: '',
          max: 0
        },
        appVersionsData: {
          isLoading: false,
          resultData: '',
          max: 0
        }
      }
    },
    mounted () {
      this.getEchartData()
      this.getPlatformAndVersion()
    },
    activated () {
    },
    methods: {
      getEchartData () {
        var vm = this

        vm.tendencyData.isLoading = true
        vm.osVersionsData.isLoading = true
        vm.equitmentsData.isLoading = true
        vm.appVersionsData.isLoading = true

        var params = []
        var platform = vm.selectForm.platform
        if (platform !== null && platform !== '') {
          params.push('platform=' + platform)
        }

        var version = vm.selectForm.version
        if (version !== null && version !== '') {
          params.push('platVersion=' + version)
        }

        if (vm.selectForm.dateTimePick !== null && vm.selectForm.dateTimePick !== '') {
          var startTime = vm.selectForm.dateTimePick[0]
          params.push('startTime=' + moment(startTime).format('YYYY-MM-DD HH:mm:ss'))

          var endTime = vm.selectForm.dateTimePick[1]
          params.push('endTime=' + moment(endTime).format('YYYY-MM-DD HH:mm:ss'))
        }

        var url = '/crash/analysis'
        url += (params.length > 0 ? '?' + params.join('&') : '')
        // console.log(url)

        vm.$http({
          url: vm.$http.adornUrl(url),
          method: 'get',
          params: vm.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            // console.log(data)
            vm.crashRate = (data.data.crashRate * 100).toFixed(7)
            vm.crashCnt = data.data.crashCnt
            vm.crashUserCnt = data.data.crashUserCnt
            vm.userCnt = data.data.userCnt

            var series = data.data.series
            vm.tendencyData.dateList = series.map(item => item.dt)
            vm.tendencyData.userCounts = series.map(item => item.cnt)

            var topOsVersion = data.data.topOsVersion
            vm.osVersionsData.max = topOsVersion.length > 0 ? topOsVersion[0].cnt : 0
            vm.osVersionsData.resultData = topOsVersion.reverse()

            var topDevice = data.data.topDevice
            vm.equitmentsData.max = topDevice.length > 0 ? topDevice[0].cnt : 0
            vm.equitmentsData.resultData = topDevice.reverse()

            var topAppVersion = data.data.topAppVersion
            vm.appVersionsData.max = topAppVersion.length > 0 ? topAppVersion[0].cnt : 0
            vm.appVersionsData.resultData = topAppVersion.reverse()

            vm.initEcharts()
          }
        })
      },
      getPlatformAndVersion () {
        var vm = this
        vm.$http({
          url: vm.$http.adornUrl('/crash/getPlats'),
          methods: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            let resultData = data.data
            vm.selectForm.platforms = []
            for (var attr in resultData) {
              var obj = {'label': attr, 'value': attr, versions: resultData[attr]}
              vm.selectForm.platforms.push(obj)
            }
          }
        })
      },
      // 初始化图表
      initEcharts () {
        var vm = this
        setTimeout(() => {
          vm.echarts.tendency = echarts.init(document.getElementById('tendency-echart'))
          vm.echarts.osVersions = echarts.init(document.getElementById('os-versions-echart'))
          vm.echarts.equitments = echarts.init(document.getElementById('equitments-echart'))
          vm.echarts.appVersions = echarts.init(document.getElementById('app-versions-echart'))
          vm.getTendencyData()
          vm.getOsVersionsData()
          vm.getEquitmentsData()
          vm.getAppVersionsData()
          window.addEventListener('resize', () => {
            vm.echarts.tendency.resize()
            vm.echarts.osVersions.resize()
            vm.echarts.equitments.resize()
            vm.echarts.appVersions.resize()
          })
        }, 100)
      },
      // 获取趋势图数据
      getTendencyData () {
        var vm = this
        var option = {
          title: {
            show: false,
            text: '暂无数据',
            top: '35%',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            top: 0,
            data: ['各小时影响用户数'],
            itemGap: 10
          },
          color: [vm.rankColor],
          dataZoom: [{
            type: 'inside',
            start: 0,
            end: 100
          }],
          xAxis: {
            boundaryGap: false,
            data: vm.tendencyData.dateList
          },
          yAxis: {
            name: '单位（人）',
            axisTick: {
              interval: 0
            },
            splitLine: {
              show: false
            }
          },
          grid: {
            top: '12%',
            left: '5%',
            right: '7%'
          },
          series: [{
            name: '各小时影响用户数',
            type: 'line',
            showSymbol: false,
            data: vm.tendencyData.userCounts,
            markLine: {
              data: [{
                type: 'average',
                name: '平均值'
              }]
            }
          }]
        }

        if (vm.tendencyData.userCounts.length < 1) {
          option.title.show = true
        }
        vm.echarts.tendency.setOption(option)
        vm.tendencyData.isLoading = false
      },
      // 获取操作系统版本影响数据
      getOsVersionsData () {
        var vm = this
        // vm.sortTop5Data()
        var option = {
          title: [{
            text: '操作系统版本Top 5',
            top: 8,
            left: 5,
            textStyle: {
              fontSize: 14,
              fontWeight: 600
            }
          }, {
            show: false,
            text: '暂无数据',
            top: 'center',
            left: 'center',
            textStyle: {
              fontSize: 12
            }
          }],
          grid: [{
            top: 35,
            left: 10,
            bottom: 3,
            right: 30
          }],
          // color: [vm.rankColor],
          color: ['#00A65A'],
          xAxis: {
            type: 'value',
            max: vm.max,
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            axisLabel: {show: false}
          },
          yAxis: {
            type: 'category',
            data: vm.osVersionsData.resultData.map(function (item) {
              return item.platform + '/' + item.platVersion
            }),
            axisLabel: {
              interval: 0,
              inside: true,
              margin: 0,
              padding: [0, 0, 25, 0]
            },
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            max: 4
          },
          series: [{
            type: 'bar',
            stack: 'chart',
            z: 3,
            label: {
              normal: {
                position: 'right',
                show: true,
                formatter: function (item) {
                  return item.cnt
                }
              }
            },
            barWidth: 10,
            data: vm.osVersionsData.resultData.map(function (item) {
              return item.cnt
            })
          }, {
            type: 'bar',
            stack: 'chart',
            silent: true,
            itemStyle: {
              normal: {
                color: '#eee'
              }
            },
            barWidth: 10,
            data: vm.osVersionsData.resultData.map(function (item) {
              return vm.osVersionsData.max - item.cnt
            })
          }]
        }

        if (vm.osVersionsData.resultData.length < 1) {
          option.title[1].show = true
        }
        vm.echarts.osVersions.setOption(option)
        vm.osVersionsData.isLoading = false
      },
      // 获取设备影响数据
      getEquitmentsData () {
        var vm = this
        var option = {
          title: [{
            text: '设备Top 5',
            top: 8,
            left: 5,
            textStyle: {
              fontSize: 14,
              fontWeight: 600
            }
          }, {
            show: false,
            text: '暂无数据',
            top: 'center',
            left: 'center',
            textStyle: {
              fontSize: 12
            }
          }],
          grid: [{
            top: 35,
            left: 10,
            bottom: 3,
            right: 30
          }],
          // color: [vm.rankColor],
          color: ['#02C0EF'],
          xAxis: {
            type: 'value',
            max: vm.max,
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            axisLabel: {show: false}
          },
          yAxis: {
            type: 'category',
            data: vm.equitmentsData.resultData.map(function (item) {
              return item.deviceBrand
            }),
            axisLabel: {
              interval: 0,
              inside: true,
              margin: 0,
              padding: [0, 0, 25, 0]
            },
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            max: 4
          },
          series: [{
            type: 'bar',
            stack: 'chart',
            z: 3,
            label: {
              normal: {
                position: 'right',
                show: true,
                formatter: function (item) {
                  return item.cnt
                }
              }
            },
            barWidth: 10,
            data: vm.equitmentsData.resultData.map(function (item) {
              return item.cnt
            })
          }, {
            type: 'bar',
            stack: 'chart',
            silent: true,
            itemStyle: {
              normal: {
                color: '#eee'
              }
            },
            barWidth: 10,
            data: vm.equitmentsData.resultData.map(function (item) {
              return vm.equitmentsData.max - item.cnt
            })
          }]
        }

        if (vm.equitmentsData.resultData.length < 1) {
          option.title[1].show = true
        }
        vm.echarts.equitments.setOption(option)
        vm.equitmentsData.isLoading = false
      },
      // 获取应用版本影响数据
      getAppVersionsData () {
        var vm = this
        var option = {
          title: [{
            text: '应用版本Top 5',
            top: 8,
            left: 5,
            textStyle: {
              fontSize: 14,
              fontWeight: 600
            }
          }, {
            show: false,
            text: '暂无数据',
            top: 'center',
            left: 'center',
            textStyle: {
              fontSize: 12
            }
          }],
          grid: [{
            top: 35,
            left: 10,
            bottom: 3,
            right: 30
          }],
          // color: [vm.rankColor],
          color: ['#F39C12'],
          xAxis: {
            type: 'value',
            max: vm.max,
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            axisLabel: {show: false}
          },
          yAxis: {
            type: 'category',
            data: vm.appVersionsData.resultData.map(function (item) {
              return item.appVersion
            }),
            axisLabel: {
              interval: 0,
              inside: true,
              margin: 0,
              padding: [0, 0, 25, 0]
            },
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            max: 4
          },
          series: [{
            type: 'bar',
            stack: 'chart',
            z: 3,
            label: {
              normal: {
                position: 'right',
                show: true,
                formatter: function (item) {
                  return item.cnt
                }
              }
            },
            barWidth: 10,
            data: vm.appVersionsData.resultData.map(function (item) {
              return item.cnt
            })
          }, {
            type: 'bar',
            stack: 'chart',
            silent: true,
            itemStyle: {
              normal: {
                color: '#eee'
              }
            },
            barWidth: 10,
            data: vm.appVersionsData.resultData.map(function (item) {
              return vm.appVersionsData.max - item.cnt
            })
          }]
        }

        if (vm.appVersionsData.resultData.length === 0) {
          option.title[1].show = true
        }
        vm.echarts.appVersions.setOption(option)
        vm.appVersionsData.isLoading = false
      },
      changePlatforms (value) {
        var vm = this
        if (value !== '') {
          let platforms = vm.selectForm.platforms
          platforms.forEach((item) => {
            if (item.value === value) {
              vm.selectForm.versions = item.versions
            }
          })
        } else {
          vm.selectForm.versions = ''
        }
        vm.selectForm.version = ''
        // vm.getEchartData()
      }
    }
  }
</script>
<style scoped>
  .select-box, .breakdown-data, .breakdown-tendency{
    border-bottom: 1px solid #eee;
  }
  .breakdown-container .select-box{
    text-align: right;
  }
  .select-box .el-select{
    width: 100px;
  }
  .select-box .el-date-picker{
    width: 372px;
  }
  .select-box .el-button{
    padding: 8px 15px;
    font-size: 14px;
  }
  .breakdown-data .el-row{
    margin-bottom: 15px;
  }
  .breakdown-data .el-col{
    border-radius: 5px;
    color: #fff;
  }
  .breakdown-data .el-col span{
    display: block;
    text-align: center;
  }
  .breakdown-data .el-col span label{
    font-size: 20px;
    font-weight: bold;
  }
  .breakdown-data .el-col .figure{
    padding: 10px 0;
  }
  .breakdown-data .el-col .declare{
    /* color: #666; */
    color: #fff;
    margin-bottom: 15px;
  }
  .breakdown-rank .top5-box{
    margin-top: 15px;
  }
  .breakdown-rank .top5-box .el-col div{
    border: 1px solid #eee;
  }
</style>
